<template>
    <el-dialog v-model="show" :title="(props.editType === 1 ? '编辑' : '') + '采购申请单'" width="700px" align-center
        @close="handleClose">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
            status-icon>
            <div class="main_dialog">
                <div class="flex-l-s wrap">
                    <div class="flex-h-s">
                        <el-form-item label="采购单号:">{{ props.initList.purchaseOrderCode || '' }}</el-form-item>
                        <el-form-item label="制单日期:">{{ props.initList.applyDate || '' }}</el-form-item>
                        <el-form-item label="规格名称:">{{ props.initList.specsDetail || '' }}</el-form-item>
                        <el-form-item label="申请数量:">{{ props.initList.number || '' }}
                            {{ getUnitLabel(props.initList.auxiliaryUnit) }}</el-form-item>
                    </div>
                    <div>
                        <div class="flex">
                            <el-form-item label="效果图:">
                                <el-image class="img_effect" lazy :src="props.initList.imageUrl" preview-teleported
                                    :preview-src-list="[props.initList.imageUrl]" fit="cover" />
                            </el-form-item>
                        </div>
                    </div>
                </div>

                <div class="flex">
                    <el-form-item label="采购数量:" prop="purchaseNumber">
                        <el-input v-model="ruleForm.purchaseNumber" type="number" placeholder="请输入">
                            <template #append>
                                <el-form-item prop="purchaseUnit">
                                    <el-select v-model="ruleForm.purchaseUnit" style="width: 80px" placeholder="请选择单位">
                                        <el-option v-for="dict in unit_enumeration" :key="dict.value"
                                            :label="dict.label" :value="dict.value" />
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="单价:" prop="purchasePrice">
                        <el-input v-model="ruleForm.purchasePrice" type="number" placeholder="请输入">
                            <template #append>元 /
                                {{ unit_enumeration.filter((item: any) =>
                                    item.value === ruleForm.purchaseUnit)[0].label }}
                            </template>
                        </el-input>
                    </el-form-item>
                </div>

                <div class="flex ">
                    <el-form-item prop="targetNumber" :label="`换算: 1 ${getUnitLabel(props.initList.auxiliaryUnit)}`">
                        <el-input class="mr20" type="number" v-model="ruleForm.targetNumber" style="width: 160px"
                            placeholder="请输入换算数量" />
                    </el-form-item>

                    <el-form-item label="输入新的单位:">
                        {{ props.initList.number || '' }}
                        {{ getUnitLabel(props.initList.auxiliaryUnit) }}
                        = {{ ruleForm.targetNumber ? Number(ruleForm.targetNumber) * Number(props.initList.number) : ''
                        }}
                        {{ getUnitLabel(ruleForm.purchaseUnit) }}
                    </el-form-item>

                </div>

                <div class="flex ">
                    <el-form-item prop="supplyFactoryId" label="供应商:">
                        <el-select v-model="ruleForm.supplyFactoryId" placeholder="请选择供应商">
                            <el-option v-for="item in props.suppliersList" :key="item.id" :label="item.companyName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="交付周期:">{{ ruleForm.supplyFactoryId ? props.suppliersList.filter((item: any) =>
                        item.id
                        ===
                        ruleForm.supplyFactoryId)[0].deliveryCycle + '天' : '' }}</el-form-item>
                </div>

                <el-form-item prop="remark" label="备注:">
                    <el-input style="width: 100%;" v-model="ruleForm.remark" placeholder="请输入备注" />
                </el-form-item>

                <el-form-item v-if="props.editType == 2" prop="approvalRemark" label="审批备注:">
                    <el-input v-model="ruleForm.approvalRemark" placeholder="请输入审批备注" />
                </el-form-item>

                <div class="flex-l-s ">
                    <el-form-item label="总计金额:">￥{{ ruleForm.purchasePrice && ruleForm.purchaseNumber ?
                        Number(ruleForm.purchasePrice) *
                        Number(ruleForm.purchaseNumber) : 0 }}</el-form-item>
                    <div>
                        <el-checkbox v-model="ruleForm.prePaymentFlag" label="先付款" size="large" />
                    </div>
                </div>

                <div v-if="props.editType == 2">
                    <div class="flex-l-s ">
                        <el-form-item label="审批人:">{{ props.initList.approvalPersonName || '' }}</el-form-item>
                        <el-form-item label="审批时间:">{{ props.initList.approvalDate || '' }}</el-form-item>
                    </div>
                </div>
            </div>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <template v-if="props.editType == 1">
                    <el-button :loading="loading" @click="handleClose">取 消</el-button>
                    <el-button type="primary" :loading="loading" @click="handleSubmit(ruleFormRef)">保 存</el-button>
                </template>
                <template v-else>
                    <el-button :loading="loading" @click="handleRefuse(ruleFormRef)">拒 绝</el-button>
                    <el-button :loading="loading" type="primary" @click="handleAgree(ruleFormRef)">同 意</el-button>
                </template>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, toRefs } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { editPurchaseRequestFormApi, approvalPurchaseRequestFormApi } from '@/api/sj/purchaseManagement/applicationForm/index';
import { ApplicationFormVO } from '@/api/sj/purchaseManagement/applicationForm/types';
import { getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance() as any;
const props = defineProps(['visible', 'initList', 'editType', 'suppliersList']);
const emits = defineEmits(['submit', 'close', 'agree', 'refuse']);
const { unit_enumeration } = toRefs(proxy?.useDict('unit_enumeration'));

const show = ref(false);
const loading = ref<boolean>(false);

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<ApplicationFormVO>({
    supplyFactoryId: '',
    purchaseUnit: '',
    targetNumber: '',
    purchasePrice: '',
    purchaseNumber: '',
    remark: '',
    prePaymentFlag: '',
    approvalRemark: '',
});

const rules = reactive<FormRules>({
    supplyFactoryId: [
        { required: true, message: '请选择供应商', trigger: ['change', 'blur'] },
    ],
    targetNumber: [
        { required: true, message: '请输入换算数量', trigger: 'blur' },
    ],
    purchasePrice: [{ required: true, message: '请输入单价', trigger: 'blur' },],
    purchaseNumber: [
        { required: true, message: '请输入采购数量', trigger: 'blur' },
    ],
});

// 辅助函数获取单位标签
const getUnitLabel = (unitValue: string): string => {
    const unit = unit_enumeration.value?.find((item: any) => item.value === unitValue);
    return unit?.label || '';
};

watch(() => props.visible, async (newValue) => {
    show.value = newValue;
    if (newValue) {
        // 使用 Object.assign 来简化对象赋值
        Object.assign(ruleForm, pick(props.initList, Object.keys(ruleForm)));

        // 特殊处理 prePaymentFlag
        ruleForm.prePaymentFlag = props.initList.prePaymentFlag == 1 ? true : false;
        ruleForm.purchaseUnit = ruleForm.purchaseUnit || '1';
    }
}, { deep: true });

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true;

            console.log(ruleForm.prePaymentFlag, '======');

            const query = {
                id: props.initList.id,
                purchaseUnit: ruleForm.purchaseUnit,
                purchasePrice: ruleForm.purchasePrice,
                purchaseNumber: ruleForm.purchaseNumber,
                targetNumber: ruleForm.targetNumber,
                remark: ruleForm.remark,
                prePaymentFlag: ruleForm.prePaymentFlag ? 1 : 0,
                supplyFactoryId: ruleForm.supplyFactoryId,
            };

            try {
                const { code } = await editPurchaseRequestFormApi(query);

                if (code === 200) {
                    loading.value = false;
                    proxy?.$modal.msgSuccess('保存成功');
                    emits('submit', true);
                    handleClose();
                }
            } catch (error) {
                loading.value = false;
            }
        } else {
            console.log('error submit!', fields)
        }
    })
};

// 辅助函数，用于从源对象中提取指定键的属性
function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Partial<T> {
    return keys.reduce((acc, key) => {
        if (obj[key] !== undefined) {
            acc[key] = obj[key];
        }
        return acc;
    }, {} as Partial<T>);
};

const handleClose = () => {
    ruleFormRef.value?.resetFields();
    emits('close');
};

/** 审批拒绝 */
const handleRefuse = (formEl: FormInstance | undefined) => {
    approvalSubmission(formEl, 3)
};

/** 审批同意 */
const handleAgree = (formEl: FormInstance | undefined) => {
    approvalSubmission(formEl, 2)
};

/** 审批接口提交 */
const approvalSubmission = async (formEl: FormInstance | undefined, type: number) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true;

            const query = {
                id: props.initList.id,
                approvalRemark: ruleForm.approvalRemark,
                approvalStatus: type,
                purchaseUnit: ruleForm.purchaseUnit,
                purchasePrice: ruleForm.purchasePrice,
                purchaseNumber: ruleForm.purchaseNumber,
                targetNumber: ruleForm.targetNumber,
                remark: ruleForm.remark,
                prePaymentFlag: ruleForm.prePaymentFlag ? 1 : 0,
                supplyFactoryId: ruleForm.supplyFactoryId,
            };

            try {
                const { code } = await approvalPurchaseRequestFormApi(query);

                if (code === 200) {
                    loading.value = false;
                    if (type == 2) {
                        proxy?.$modal.msgSuccess('审批保存成功');
                    } else {
                        proxy?.$modal.msgSuccess('申请单已拒绝');
                    }
                    emits('agree');
                    handleClose();
                }
            } catch (error) {
                loading.value = false;
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

onMounted(() => {
});
</script>

<style lang="scss" scoped>
.main_dialog {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;

    .flex-l-s {
        display: flex;
        justify-content: space-between;
    }

    .flex-h-s {
        display: flex;
        justify-content: space-between;
        flex-direction: column;
    }

    .wrap {
        flex-wrap: wrap;
    }

    .flex {
        display: flex;
        align-items: center;
    }

    .label {
        font-weight: bold;
        font-size: 16px;
        color: #000;
        box-sizing: border-box;
    }

    .value {
        font-size: 16px;
        font-weight: bold;
        color: #000;
    }

    .img_effect {
        width: 180px;
        height: 180px;
        object-fit: cover;
    }

    .num_text {
        color: red;
    }
}
</style>